﻿using UnityEngine;
using UnityEngine.UI;
using System.Collections.Generic;
using UnityEngine.EventSystems;

public class LoopScrollView : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
{
    [SerializeField] private Texture[] roomTextures; //所有卡片
    [SerializeField] private GameObject itemPrefab; //列表项预制体
    [SerializeField] private Transform itemParent; //列表项的父级，将卡片生成到该物体下
    [SerializeField] private Button prevButton; //上一个按钮
    [SerializeField] private Button nextButton; //下一个按钮
    [SerializeField] private float interval = 400f; //卡片之间的间距

    //生成的卡片列表
    public  List<LoopScrollViewItem> itemList = new List<LoopScrollViewItem>();
    //字典用于存储各位置对应的卡片层级和坐标
    private readonly Dictionary<int, LoopScrollViewData> map = new Dictionary<int, LoopScrollViewData>();
    public int indexs;
    private void Start()
    {
        //for (int i = 0; i < roomTextures.Length; i++)
        //{
        //    var tex = roomTextures[i];
        //    var instance = Instantiate(itemPrefab);
        //    instance.SetActive(true);
        //    instance.transform.SetParent(itemParent, false);
        //    instance.GetComponent<RawImage>().texture = tex;
        //    instance.name = i.ToString();


        //    //坐标位置  横向是right  要想竖向就是up
        //    (instance.transform as RectTransform).anchoredPosition3D = Vector3.right * interval
        //        * (i <= roomTextures.Length / 2 ? i : (i - roomTextures.Length));
        //    //层级关系
        //    instance.transform.SetSiblingIndex(i <= roomTextures.Length / 2 ? 0 : itemParent.childCount - 2);
        //    //大小
        //    instance.transform.localScale = (i == 0 ? 1.2f : 1f) * Vector3.one;

        //    var item = instance.AddComponent<LoopScrollViewItem>();
        //    item.Index = i;
        //    itemList.Add(item);
        //}
        //for (int i = 0; i < itemList.Count; i++)
        //{
        //    var item = itemList[i];
        //    map.Add(i, new LoopScrollViewData(item.transform.GetSiblingIndex(), (item.transform as RectTransform).anchoredPosition3D));
        //}
        InitializeItems();
        //添加按钮点击事件
        nextButton.onClick.AddListener(OnNextButtonClick);
        prevButton.onClick.AddListener(OnPrevButtonClick);
    }
    private void OnEnable()
    {
        InitializeItems();
    }

    // 封装初始化逻辑
    private void InitializeItems()
    {
        // 清空之前的 map 数据
        map.Clear();

        for (int i = 0; i < roomTextures.Length; i++)
        {
            var tex = roomTextures[i];
            GameObject instance;
            if (i < itemList.Count)
            {
                // 复用已有的 item
                instance = itemList[i].gameObject;
            }
            else
            {
                // 如果 item 数量不够，生成新的 item
                instance = Instantiate(itemPrefab);
                instance.SetActive(true);
                instance.transform.SetParent(itemParent, false);
                var item = instance.AddComponent<LoopScrollViewItem>();
                itemList.Add(item);
            }

            instance.GetComponent<RawImage>().texture = tex;
            instance.name = i.ToString();

            // 坐标位置  横向是 right  要想竖向就是 up
            (instance.transform as RectTransform).anchoredPosition3D = Vector3.right * interval
                * (i <= roomTextures.Length / 2 ? i : (i - roomTextures.Length));
            // 层级关系
            instance.transform.SetSiblingIndex(i <= roomTextures.Length / 2 ? 0 : itemParent.childCount - 2);
            // 大小
            instance.transform.localScale = (i == 0 ? 1.2f : 1f) * Vector3.one;

            var itemComponent = instance.GetComponent<LoopScrollViewItem>();

            itemComponent.loopScrollView =transform.GetComponent<LoopScrollView>() ;

            itemComponent.Index = i;
        }

        // 更新 map 数据
        for (int i = 0; i < itemList.Count; i++)
        {
            var item = itemList[i];
            map[i] = new LoopScrollViewData(item.transform.GetSiblingIndex(), (item.transform as RectTransform).anchoredPosition3D);
        }
    }
    // 跳转到指定索引位置的方法
    // 跳转到指定索引位置的方法
    // 跳转至指定页面的方法
    public void JumpToPage(int targetPageIndex)
    {
        if (targetPageIndex < 0 || targetPageIndex >= itemList.Count)
        {
            Debug.LogError("Target page index is out of range.");
            return;
        }

        for (int i = 0; i < itemList.Count; i++)
        {
            var item = itemList[i];
            bool last = item.Index == itemList.Count / 2;
            item.Index = targetPageIndex;
            item.Move(map[targetPageIndex], last);
        }
    }
    //下一个按钮点击事件
    private void OnNextButtonClick()
    {
        for (int i = 0; i < itemList.Count; i++)
        {
            var item = itemList[i];
            bool last = item.Index == itemList.Count / 2;
            int index = item.Index + 1;
            index = index >= itemList.Count ? 0 : index;
            item.Index = index;
            item.Move(map[index], last);



          
        }
    }
    //上一个按钮点击事件
    private void OnPrevButtonClick()
    {
        for (int i = 0; i < itemList.Count; i++)
        {
            var item = itemList[i];
            int index = item.Index - 1;
            index = index < 0 ? itemList.Count - 1 : index;
            item.Index = index;
            item.Move(map[index], false);

          
        }
        
    }


    private Vector2 initialPosition;

    public void OnBeginDrag(PointerEventData eventData)
    {
        // 记录滑动开始时的初始位置
        initialPosition = eventData.position;
    }

    public void OnDrag(PointerEventData eventData)
    {
        // 无需在拖动时执行任何操作
    }

    public void OnEndDrag(PointerEventData eventData)
    {
        // 获取滑动结束时的位置
        Vector2 finalPosition = eventData.position;

        // 计算滑动方向
        Vector2 direction = finalPosition - initialPosition;

        // 根据滑动方向调用相应的按钮点击事件
        if (direction.x < -1)  // 向左滑动
        {
            OnPrevButtonClick();
        }
        else if (direction.x > 1)  // 向右滑动
        {
            OnNextButtonClick();
        }
    }
  

}
